<? defined('SYSPATH') or die('No direct script access');

class Event_Controller extends Template_Controller {

     // Set the name of the template to use
    public $template = 'kohana/template';
    
    /**
     * Retrieve user id of current user
     * @return integer id for current user
     */
    private function _get_current_user_id(){
        return 1; //NEED TO BE MODIFIED 
    }

    /**
     * Get default value of fields for creating a new event.
     * @return array return detail information regarding to the event
     */
    public function _get_edit_form_default_values(){
        $form=array(
            // Fields from EVENT_DETAILS table
            'event_id'=>'',
            'name'=>'',
            'description'=>'',
            'start_time'=>time(),
            'end_time'=>time(),
            'scope'=>'P',
            'host_name'=>'',
            'phone'=>'',
            'email'=>'',
            
            // Fields from EVENT_LOCATIONS table
            'street'=>'',
            'city'=>'',
            'state'=>'MA',
            'zip_code'=>'',
        );
        return $form;      
    }
    /**
     * Add or edit a event
     * @param integer event id parameter, if no specified, it defaults to null
     * @return null
     */
    public function index($event_id=null)
    {
        // Create model
        $event= new Event_Model();  
        $user_id=$this->_get_current_user_id();      
        
        if ($event_id==null){
            $form=$this->_get_edit_form_default_values();
        }
        else{
            $resultset=$event->get_event_detail($event_id);
            //If retrieved event is not own by current user, create a new event instead
            if($resultset==null || $resultset->event->user_id!=$user_id){
                $event_id=null;
                $form=$this->_get_edit_form_default_values(); 
            }
            else{
                $form=array_merge(
                    get_object_vars($resultset->event), 
                    get_object_vars($resultset->location));
                $form['event_id']=$event_id;
            }
        }
        // Create view
        $view= new View('event/event_edit');        
        $view->form=$form;
        $this->template->content = $view;
        $this->template->title = ($event_id==null?'Add New Event':'Edit Existing Event');
        //echo $view->render();  <-- we'd use this for a normal Controller
    }
    
    /**
     * Add or edit a event, same as index function
     * @param integer event id parameter, if no specified, it defaults to null
     * @return null
     */
    public function edit($event_id=null){
        $this->index($event_id);          
    }
    
    /**
     * Save the event posted by event_edit form
     * @return null
     */
    public function save(){

        $event_id=$this->input->post('event_id');

        $post = new Validation($_POST);
        $post->add_rules('start_date','required','valid::date');
        $post->add_rules('end_date','required','valid::date');
        $post->add_rules('phone', 'valid::phone[10]');        
        $post->add_rules('email', 'valid::email');
        $post->add_rules('zip_code','length[5]','valid::digit');

        
        $name= $this->input->post('name');
        $description= $this->input->post('description');
        $start_date= $this->input->post('start_date');
        $start_time=$this->input->post('start_time');
        $end_date= $this->input->post('end_date');
        $end_time=$this->input->post('end_time');
        
        $user_id=$this->_get_current_user_id();
        $scope= $this->input->post('scope');
        $host_name= $this->input->post('host_name');
        $phone= $this->input->post('phone'); 
        $email= $this->input->post('email');
        $street= $this->input->post('street');
        $city= $this->input->post('city'); 
        $state= $this->input->post('state'); 
        $zip_code= $this->input->post('zip_code');
        
        //Formate start time and end time to PHP unix timestamp
        $start_time= strtotime($start_date . $start_time);
        $end_time=strtotime($end_date . $end_time);         
         
         if(!$post->validate()){
            $error_message='';
            $errors = $post->errors();
            foreach ($errors as $key => $val)   {
                $error_message.=$key.' failed rule '.$val.'<br />';
            }
            // Create view
            $view= new View('event/event_edit'); 
            $form=$post->as_array();
            $form['start_time']=$start_time;
            $form['end_time']=$end_time;       
            $view->form=$form;
            $view->error_message=$error_message;
            $this->template->content = $view;
            $this->template->title = ($event_id==null?'Add New Event':'Edit Existing Event');
            return;
        }




        
        $event=new Event_Model(); 
        $success=true; 
        
        if($event_id!=''){
            $this->template->title = 'Existing Event Saved'; 
            $success=$event->update_event($user_id, $event_id, $name, $description,
                $start_time, $end_time, 
                $scope, $host_name, $phone, $email,
                $street, $city, $state, $zip_code);
                
        }else{
             $this->template->title = 'New Event Saved'; 
             $event_id=$event->add_event($user_id, $name, $description, 
                $start_time, $end_time, 
                $scope, $host_name, $phone, $email,
                $street, $city, $state, $zip_code);
        }
        if(!$success){
            $this->template->content =" Error: Failed to update event with id=$event_id!";
        }
        else{
            $this->template->content =" Event with id=$event_id is successfully saved!";
        }
            
    }
    
    public function event_list(){
        // Create view
        $view= new View('event/event_list');

        // Create model
        $event = new Event_Model();

        $user_id=$this->_get_current_user_id();
        $view->event_list =  $event->get_event_list($user_id,time(),time()) ;   

        $this->template->content = $view;
        $this->template->title = 'Event List Page';
    }
    public function event_detail($event_id=null){
        // Create model
        $event = new Event_Model();
        $user_id=$this->_get_current_user_id();
        
        $this->template->title = 'Event Detail Page';
        $success=false;        
        if ($event_id != null && $event->can_view_event($event_id, $user_id)){
            $event_detail=$event->get_event_detail($event_id);  
            if($event_detail!=null){
                // Create view               
                $view= new View('event/event_detail');                 
                $view->event_detail = $event_detail;
                $this->template->content = $view;               
                $success=true;
            }
        }
        if(!$success){
            $this->template->content = "Error: the event is not viewable by current user!";
        }
    }
    
    public function delete($event_id=null){
        $event=new Event_Model(); 
        $this->template->title="Delete Event";
        $user_id=$this->_get_current_user_id();
        $success=false;
        if ($event_id!=null && $event->delete_event($event_id, $user_id)){
            $success=true;
        } 
        
        if($event_id==null){
            $result="Error: Need to specify event id as argument!";
        }
        elseif(!$success){
            $result="Error: Failed to delete event with id = $event_id!";
        }
        else{
            $result="Event with id= $event_id is deleted from database.";
        }
        $this->template->content=$result;

    }
    
    public function test(){
        $this->template->title="Test function"; 
   
       
       // Create view               
       $view= new View('event/event_test');    
       $this->template->content=$view;
        
    }
}

?>

